﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SCRUM.Core.DAO;
using SCRUM.Core.Exceptions.Database;
using SCRUM.Core.BusinessObjects;

/// <summary>
/// Widget to manage calendar events, Availability of users in time.
/// </summary>
public partial class AvailabilityWidget : WidgetBase
{
    /// <summary>
    /// Gets the name of the widget. It must be exactly the same as the folder that contains the widget.
    /// </summary>
    /// <value>PrototypeWidget</value>
    public override string Name
    {
        get { return "AvailabilityWidget"; }
    }

    /// <summary>
    /// Gets the title. Title is shown in the header of the widget container.
    /// </summary>
    /// <value>The title.</value>
    public override string Title
    {
        get { return (string)GetLocalResourceObject("Title"); }
    }


    /// <summary>
    /// This method works as a substitute for Page_Load. You should use this method for
    /// data binding etc. instead of Page_Load.
    /// </summary>
    public override void LoadWidget()
    {
        if (!IsPostBack)
        {
            this.PickFrom.SeledtedDate = DateTime.Today.Date;
            this.PickTo.SeledtedDate = DateTime.Today.Date.AddMonths(1);
            ButtonAdd.Visible = false;
        }
        Details.Visible = false;
    }

    /// <summary>
    /// /// Sets handlers for events.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    public void Page_Init(object sender, EventArgs e)
    {
    }

    /// <summary>
    /// Loads content of the gridview with availabilities acording to filters
    /// </summary>
    private void LoadAvailabilityForDates()
    {
        List<Availability> availabilities = new List<Availability>();
        availabilities = DAOAvailability.GetAvailabilities(PickFrom.SeledtedDate.Value, PickTo.SeledtedDate.Value);
        if (availabilities != null)
        {
            this.GridViewAvailability.DataSource = availabilities;
            this.GridViewAvailability.DataBind();
        }
    }

    /// <summary>
    /// User is going to create new availability
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    public void ShowCreateArea(object sender, EventArgs e)
    {
        DisplayDetails(null);
        ButtonEdit.Visible = false;
        ButtonCancel.Visible = true;
        ButtonAdd.Visible = true;
    }

    /// <summary>
    /// Deletes the availability.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="ce">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
    public void DeleteAvailability(object sender, CommandEventArgs ce)
    {
        int avaID = Int32.Parse((string)ce.CommandArgument);
        try
        {
            DAOAvailability.DeleteAvailability(avaID);
            this.LoadAvailabilityForDates();
            ShowOperationResult(MessageType.Info, "ItemDeleted");
        }
        catch (InconsistentDatabaseException e)
        {
            ShowOperationResult(MessageType.Error, e.Message);
        }
        LoadWidget();
    }

    /// <summary>
    /// Edits the Availability.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="ce">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
    public void EditAvailability(object sender, CommandEventArgs ce)
    {
        int avaID = Int32.Parse((string)ce.CommandArgument);
        ViewState["EdittingAvailabilityID"] = avaID;
        Availability ava = DAOAvailability.GetAvailabilityByID(avaID);
        DisplayDetails(ava);
    }

    /// <summary>
    /// Displays the Availability
    /// </summary>
    /// <param name="ava">The Availability.</param>
    private void DisplayDetails(Availability ava)
    {
        Details.Visible = true;
        if (ava != null)
        {
            StartDate.SeledtedDate = ava.FromDateTime;
            EndDate.SeledtedDate = ava.ToDateTime;
            InputName.Text = ava.Name;
            InputDescription.Text = ava.Description;
        }
        else
        {
            StartDate.SeledtedDate = DateTime.Today.Date;
            EndDate.SeledtedDate = DateTime.Today.Date;
			InputName.Text = String.Empty;
			InputDescription.Text = String.Empty;
        }
    }

    #region [ Settings ]

    /// <summary>
    /// Gets a value indicating whether this instance is editable.
    /// </summary>
    /// <value>
    /// 	<c>true</c> if this instance is editable; otherwise, <c>false</c>.
    /// </value>
    public override bool IsEditable
    {
        get { return false; }
    }

    /// <summary>
    /// Shows the edit.
    /// </summary>
    public override void ShowEdit()
    {
        base.ShowEdit();
    }

    /// <summary>
    /// Hides the edit.
    /// </summary>
    public override void HideEdit()
    {
        base.HideEdit();
    }
    #endregion

    /// <summary>
    /// Changes selection of grid and shows details
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void GridViewAvailability_SelectedIndexChanged(object sender, EventArgs e)
    {
		Availability ava = DAOAvailability.GetAvailabilityByID(
			(int)this.GridViewAvailability.SelectedDataKey.Value);
		DisplayDetails(ava);
        ButtonEdit.Visible = true;
        ButtonAdd.Visible = false;
    }

    /// <summary>
    /// User confirmed filters
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Apply_Click(object sender, EventArgs e)
    {
        if (PickFrom.SeledtedDate > PickTo.SeledtedDate)
        {
            DateTime tmp = this.PickTo.SeledtedDate.Value;
            this.PickTo.SeledtedDate = this.PickFrom.SeledtedDate;
            this.PickFrom.SeledtedDate = tmp;
        }
        LoadAvailabilityForDates();
    }

    /// <summary>
    /// Validates dates in form. In case they are in wrong order revert order.
    /// </summary>
    private void CheckDates()
    {
        if (StartDate.SeledtedDate > EndDate.SeledtedDate)
        {
            DateTime tmp = this.EndDate.SeledtedDate.Value;
            this.EndDate.SeledtedDate = this.StartDate.SeledtedDate;
            this.StartDate.SeledtedDate = tmp;
        }
    }

    /// <summary>
    /// Creates new entity and refreshes the view
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void AddNewAvailability(object sender, EventArgs e)
    {
        CheckDates();
        Availability ava = new Availability(0, StartDate.SeledtedDate.Value, 
			EndDate.SeledtedDate.Value, InputName.Text, InputDescription.Text,1); 
        DAOAvailability.CreateAvailability(ava);
		this.GridViewAvailability.SelectedIndex = -1;
        LoadWidget();
    }

    /// <summary>
    /// User confirmed filters
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void CancelEditAvailability_Clicked(object sender, EventArgs e)
    {
		this.GridViewAvailability.SelectedIndex = -1;
        Details.Visible = false;
    }

    /// <summary>
    /// Saves edited values for availability
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void EditAvailability_Clicked(object sender, EventArgs e)
    {
        CheckDates();
        Availability ava = new Availability((int)GridViewAvailability.SelectedDataKey.Value, 
			StartDate.SeledtedDate.Value, EndDate.SeledtedDate.Value, InputName.Text, InputDescription.Text, 1);
        DAOAvailability.UpdateAvailability(ava);
		this.GridViewAvailability.SelectedIndex = -1;
        LoadWidget();
    }

	/// <summary>
	/// Raises the <see cref="E:System.Web.UI.Control.PreRender"/> event.
	/// </summary>
	/// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
	protected override void OnPreRender(EventArgs e)
	{
		base.OnPreRender(e);
		LoadAvailabilityForDates();
	}
}